<template>
  <div class="main">
    <div class="map">
      <div id="containCesium"></div>
      <!-- <progress-bar></progress-bar> -->
      <tool-bar
        :toolList="toolList"
        @changeToolState="changeToolState"
        @changeWidget="changeWidget"
        @changeMapThumbnail="changeMapThumbnail"
      ></tool-bar>
      <!-- 工具列表 -->
      <div v-for="item in curToolList" :key="item.code">
        <component v-bind:is="item.app" @close="changeToolState"  :ref="item.funcInvokeUrl"></component>
      </div>
      <!-- 其他地图微件 start -->
      <div v-for="item in curMapWdList" :key="item.code">
        <component
          v-bind:is="item.app"
          @close="changeWidget"
          :ref="item.funcInvokeUrl"
        ></component>
      </div>
      <!-- 其他工具列表 -->
      <div v-for="item in curToolList1" :key="item.code">
        <component v-bind:is="item.app" @close="changeToolState" :ref="item.funcInvokeUrl" ></component>
      </div>
    </div>
    <div id="map"></div>
    <div id="slider" class="slider" title="左右滑动，实现卷帘效果"></div>
  </div>
</template>
<script>
let AgcimLayerTree = agcim.scene.LayerTree;
import ToolBar from "@/views/components/shell/ToolBar.vue";
// import ProgressBar from "@/widgets/ProgressBar/index.vue";
import serverData4Config from "@/views/js/net/serverData4Config";
import { MapInit } from "./js/index";
import { mapWdList } from "./js/config";

let tApps = {};
let wApps = {};
let curMapWdList = [
  { code: "SurroundObservation", funcInvokeUrl: "SurroundObservation" },
  // { code: "Legend", funcInvokeUrl: "Legend" }, //图例，移到工具箱
  { code: "CesiumNavigation", funcInvokeUrl: "CesiumNavigation" }, //小罗盘部件
  { code: "LayerStyle", funcInvokeUrl: "LayerStyle" }, //图层树图层样式
  // { code: "ViewPointRotation", funcInvokeUrl: "ViewPointRotation", visible: true, widgetType: "agcim-widget-init" },
  { code: "MapThumbnail", funcInvokeUrl: "MapThumbnail" }, //地图缩略图
]; //默认开启
export default {
  name: "basic-roam",
  components: {
    "tool-bar": ToolBar,
    // "progress-bar":ProgressBar
  },
  // props: {
  //   toolList: { type: Array },
  //   // mapWdList: { type: Array }, //可后台配 , 现在是本地手动配
  // },
  data() {
    return {
      //当前打开的工具
      curToolList: [],
      //当前打开的工具，需要在地图之外
      curToolList1: [],
      //地图上的微件，可默认，可调用时开启
      curMapWdList: [],
      toolList:[]
    };
  },
  created() {
    let widgetsTimer = setInterval(()=>{
          if(agcim){
            //更新或初始化微件数据
            agcim.widgets.widgetExtendField.getOriginWidgetAllData().then(data=>{
              if(data instanceof Array && data.length>0){
                this.findFuncByUser(data);
                this.findWidgetByCode()               
              }
            })
            clearInterval(widgetsTimer);
          }
      },200)
  },
  beforeMount() {
    MapInit.createInitialSpot(); //获取默认视点
    this.initMap();
  },
  mounted() {
    /* 全局事件，供控高分析使用 */
    this.$on("changeToolState", (msg) => {
      this.changeToolState(msg);
      CIM.viewer.infoBox._element.hidden = true;
    });
  },
  methods: {
    findWidgetByCode() {
      let url = agcim.net.apiPath.findWidgetByCode;
      url += "?code=agcim-layerTreeMini";
      agcim.net.axiosWraper
        .getData(url)
        .then(response => {
          if (response.content && response.content.widgetLevelsDisabled != "1") {
            this.$store.state.showLayerTreeMini = true
          }else{
            this.$store.state.showLayerTreeMini = false
          }          
        })
        .catch(error => {
          this.$store.state.showLayerTreeMini = false
          return null;
        });
    },
        //菜单
    findFuncByUser(dataArray) {
      if (dataArray&&dataArray.length > 0) {
          dataArray.forEach((element) => {
            if (element.childrenList) {
              element.childrenList.forEach((item) => {
                let list = item.childrenList;
                if (list) {
                  if (item.code === "ag-sidebar") {
                    this.catalogueAllInfo = list;
                    // this.addRouters(list);
                  } else if (item.code === "ag-toolbox") {
                    this.toolList = list;
                    localStorage.setItem(
                      "toolItem",
                      JSON.stringify(this.toolList)
                    );
                  } else if (item.code === "ag-fastnav") {
                    this.fastnavList = list;
                  }
                }
              });
            }
          });
      } else {
        this.$message.error("接口超时，刷新浏览器再试试。");
      }
    },
    
    changeMapThumbnail(checkedKeys){
      this.$refs["MapThumbnail"][0].changeOpenState(checkedKeys);
    },
    initMap: function() {
      console.log('fdfioi=============');
      let _t = this;
      if (!window.CIM.layerTree) {
        window.CIM.layerTree = new AgcimLayerTree();
      }
      var res = _t.getLayerTreeData();
      let userInfo = this.$store.state.user;
      res
        .then((data) =>{
          this.$store.commit("changeProjectName", CIM_LAYERTREE_NAME);
          this.$store.commit("changeLayerTreeResult", data);
          MapInit.creatMap("containCesium", data, userInfo,this);
          _t.initWidgets(curMapWdList);
        })
        .catch(function(error) {
          console.log('请求错误====================');
          return;
        });
    },
    initWidgets(arr) {
      let vm = this;
      //注意底部的小罗盘，比例尺及文字
      mapWdList.forEach((item) => {
        let app = item.funcInvokeUrl;
        try {
          wApps[app] = require(`@/widgets/${app}/index.vue`).default;
        } catch (error) {
          console.log(error);
        }
      });
      this.$nextTick(() => {
        if (arr && wApps) {
          for (let i = 0; i < arr.length; i++) {
            let o = arr[i];
            if (o.code === 'ViewPointRotation') {
              this.changeToolState(o)
              continue
            }
            for (let i = 0; i < this.curMapWdList.length; i++) {
              if (this.curMapWdList[i].funcInvokeUrl === o.funcInvokeUrl) {
                return this.curMapWdList.splice(i, 1);
              }
            }
            if (!o.app) {
              o.app = wApps[o.funcInvokeUrl];
            }
            this.curMapWdList.push(o);
          }
        }
      });
    },
    changeWidget(o) {
      if (!o.funcInvokeUrl) {
        o.funcInvokeUrl = o.code;
      }
      let vm = this;
      for (let i = 0; i < vm.curMapWdList.length; i++) {
        if (vm.curMapWdList[i].funcInvokeUrl === o.funcInvokeUrl) {
          return vm.$refs[o.funcInvokeUrl][0].onShow(o);
        }
      }
      if (!o.app) {
        let newO = {
          code: o.funcInvokeUrl,
          app: wApps[o.funcInvokeUrl],
        };
        vm.curMapWdList.push(newO);
      }
      vm.$nextTick(() => {
        vm.$refs[o.funcInvokeUrl][0].onShow(o);
      });
    },

    //打开工具
    changeToolState(o) {
      if (!o.funcInvokeUrl) {
        o.funcInvokeUrl = o.code;
      }
      for (let i = 0; i < this.curToolList.length; i++) {
        //属性 不关闭
        // if (o.funcInvokeUrl == "AttributeEnquiry") {
        //   return;
        // } else
        if (this.curToolList[i].funcInvokeUrl === o.funcInvokeUrl) {
          //去掉打开状态
          for (let j = 0; j < this.toolList.length; j++) {
            //去掉属性的工具的判断
            if (this.toolList[j].funcInvokeUrl === o.funcInvokeUrl) {
              this.toolList[j].visiable = false;
              if( this.$refs[o.funcInvokeUrl][0].close &&  this.$refs[o.funcInvokeUrl][0].close instanceof Function){
                this.$refs[o.funcInvokeUrl][0].close();
              }
              continue;
            }
          }
          return this.curToolList.splice(i, 1);
        }
      }

      for (let i = 0; i < this.curToolList1.length; i++) {
        if (this.curToolList1[i].funcInvokeUrl === o.funcInvokeUrl) {
          //去掉打开状态
          for (let j = 0; j < this.toolList.length; j++) {
            //去掉属性的工具的判断
            if (this.toolList[j].funcInvokeUrl === o.funcInvokeUrl) {
              this.toolList[j].visiable = false;
              continue;
            }
          }
          if (o.funcInvokeUrl == "MultiScreenLinkage") {
            //可待某个字段区分
            document.getElementById("fastNav").style.right = "585px";
          }
          return this.curToolList1.splice(i, 1);
        }
      }

      if (!o.app) {
        if(!tApps[o.funcInvokeUrl]){
          try {
            tApps[o.funcInvokeUrl] = require(`@/widgets/${o.funcInvokeUrl}/index.vue`).default;
          } catch (e) {
            this.$message.error(`找不到指定的功能！`);
            console.error(e);
          } 
        } 
        o.app = tApps[o.funcInvokeUrl];
      }
      this.curToolList.push(o);
    },
    isEmptyObject(e) {
      for (let t in e) return !1;
      return !0;
    },
    //获取图层树数据
    async getLayerTreeData() {
      let projectName = CIM_LAYERTREE_NAME;
      let p = {
        projectName: projectName,
        emptydir: true,
        isInOuter: agcim.net.apiPath.isInOuter ? 1 : 0
      };
      
      console.log('data==========');
      let data = await serverData4Config.getLayerTreeData(p);
      return data;
    },
  },
};
</script>
<style scoped>
.main{
  width: 100%;
  height: 100%;
}
.map {
  position: relative;
  display: flex;
  height: 100%;
}
.map #containCesium {
  position: relative;
  height: 100%;
  width: 100%;
  /* flex: 1; */
}
/* .map > div {
   flex: 1;
  height: 100%;
} */
.map /deep/ .cesium-viewer-toolbar {
  top: 70px;
}

.slider {
  display: none;
  left: 50%;
  position: absolute;
  top: 0;
  z-index: 999;
  width: 8px;
  height: 100%;
  border-radius: 0 3px 3px 0px;
  background: rgb(81, 61, 192);
  z-index: 99;
  -webkit-user-select: none;
  user-select: none;
}
</style>
